import urllib2, urllib, re


def search(term,pages=1):
	end_matches = []
	term = term.replace(" ", "+")
	url = "http://www.flickr.com/search/?q=%s&page=%s"%(term,pages)

	f = urllib.urlopen(url)
	f = f.read()
	try:
		found = f.split('<div class="Found">')[1].split('<span class="queryterm">')[0]
		found = found.split()[2]
		p = re.compile('<td class="DetailPic">.*?</td>')
		matches = p.findall(f.replace("\n", ""))
		link_matches = []
		this_match = []
		for match in matches:
			a = re.compile('".*?"')
			this_match.append(a.findall(match)[1][1:-1])
			a = re.compile('<img .*?/>')
			link_matches.append( a.findall(match) )
			
		for i,match in enumerate(link_matches):
			m_split = match[0].split("\"")
			end_matches.append([m_split[1],m_split[7],this_match[i]])
	except: 
		found = 0;
	
	return (found, end_matches)
	
def image(link):
	f = open("images/image.jpg", "wb")
	f.write(urllib2.urlopen("http://static.flickr.com/"+link).read())
	f.close()
	

def tag(url):
	end_matches = []

	f = urllib.urlopen("http://www.flickr.com/%s"%url)
	f = f.read()
	
	p = re.compile('<div id="tagdiv.*?">.*?</div>')
	matches = p.findall(f.replace("\n", ""))
	link_matches = []
	this_match = []
	for match in matches:
		link = re.compile('<a.*?class="Plain">.*?</a>')
		link = link.findall(match)
		end_matches.append(link[0].split("\"")[1].split("/")[3])
		
	
	return (end_matches)
